﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.Framework.Net;
using ZyGames.Framework.RPC.Sockets;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;
using ZyGames.Framework.Game.Sns;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 修改自定义手机号的密码
	/// </summary>
	public class Action10009 : BaseAction
	{
		private int _userId;
		private bool _result = false;
		private string _log = string.Empty;
		private string _phone;
		private string _pwd;

		public Action10009(HttpGet actionGetter)
			: base((short)ActionType.DZChangPhonePwd, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetString("PhoneNum", ref _phone) &&
				httpGet.GetString("Pwd", ref _pwd))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			try
			{
				var isRegisted = GameTable.Current.CheckPhoneIsRegisted(_phone);
				if (!isRegisted)
				{
					_result = false;
					_log = "该号码尚未被注册";
					return true;
				}
				//检测密码是否符合规则
				var length = _pwd.Length;
				if (length < 6 || length > 12)
				{
					_result = false;
					_log = "密码长度要在6-12个字符";
					return true;
				}

				var user = SnsManager.GetUserInfo(_phone);
				if(user == null)
				{
					_result = false;
					_log = "手机号不存在";
					return true;
				}
				var valueNum = SnsManager.ChangePass(user.UserId.ToString(), _pwd);
				if(valueNum > 0)
				{
					var info = GameTable.Current.FindInfoByPhone(_phone);
					if(info == null)
					{
						_result = false;
						_log = "密码修改失败";
						return true;
					}
					info.ModifyLocked(() =>
					{
						info.Pwd = _pwd;
					});
					_result = true;
					_log = "密码修改成功";
					return true;
				}
				else
				{
					_result = false;
					_log = "密码修改失败";
					return true;
				}
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine("10009消息异常:" + ex.ToString());
				return false;
			}
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(_result);
			this.PushIntoStack(_log);
			this.PushIntoStack(_phone);
			this.PushIntoStack(_pwd);
		}
	}
}
